package com.dkts.oil.test.road;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONObject;

public class GaoDePortPOICrawler {

    private static final String KEY = "705684832692f18116dd0a28e55512ac"; // 请替换成你的高德Key

    public static void main(String[] args) throws Exception {
        String keywords = "机场";
        int offset = 25;  // 每页最多25条
        int page = 1;

        while (true) {
            String url = "https://restapi.amap.com/v3/place/text?keywords=" + URLEncoder.encode(keywords, "UTF-8")
//                    + "&types=190300"
                    + "&city="  // 空表示全国
                    + "&offset=" + offset
                    + "&page=" + page
                    + "&key=" + KEY;

            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            JSONObject json = new JSONObject(response.toString());

            if (!"1".equals(json.getString("status"))) {
                System.out.println(json);
                System.out.println("请求失败：" + json.getString("info"));
                break;
            }

            int count = json.getInt("count");
            if (count == 0) {
                System.out.println("没有更多数据");
                break;
            }

            JSONArray pois = json.getJSONArray("pois");

            for (int i = 0; i < pois.length(); i++) {
                JSONObject poi = pois.getJSONObject(i);
                String name = poi.getString("name");
                String location = poi.getString("location");  // 经度,纬度
                String address = poi.optString("address", "");
                System.out.println("机场名称：" + name + ", 位置：" + location + ", 地址：" + address);
            }

            // 当返回条数少于每页请求数时，认为已经到最后一页
            if (count < offset) {
                System.out.println("数据抓取完成");
                break;
            }

            page++;
            Thread.sleep(200);  // 避免请求过快
        }
    }
}
